package com.tich.gateway.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter; // 注意 reactive 包
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource; // 修正为 reactive 版本
import org.springframework.web.reactive.DispatcherHandler;
import org.springframework.web.util.pattern.PathPatternParser;

@Configuration
@ConditionalOnClass(DispatcherHandler.class)
public class GatewayCorsConfig {

    @Bean
    public CorsWebFilter corsWebFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOriginPattern("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        config.setMaxAge(3600L);

        // 使用 reactive 专用配置源
        UrlBasedCorsConfigurationSource source =
                new UrlBasedCorsConfigurationSource(new PathPatternParser()); // 注意使用 PathPatternParser
        source.registerCorsConfiguration("/**", config);

        return new CorsWebFilter(source);
    }
}